from flask import json
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# 定义全局变量  
driver = None
wait = None
options = None


def setup():
    global driver, wait, options
    # 设置Chrome启动参数  
    options = Options()
    options.add_argument("start-maximized")
    # 启动Chrome浏览器  
    driver = webdriver.Chrome(options=options)
    wait = WebDriverWait(driver, 20)


def teardown():
    # 关闭浏览器  
    if driver:
        driver.quit()


def homework_load():
    global driver, wait, options
    # 打开网址  
    driver.get("https://work.weixin.qq.com/")
    # 执行JavaScript代码，点击登录按钮  
    driver.execute_script("document.querySelector('.index_top_operation_loginBtn').click()")
    # 等待页面跳转，判断是否登录成功  
    wait.until(EC.url_contains("https://work.weixin.qq.com/wework_admin/frame"))
    # 获取登录后的cookie  
    cookies = driver.get_cookies()
    # 将cookie写入文件里  
    with open("./cookies.yml", "w") as f:
        for cookie in cookies:
            f.write(str(cookie) + "\n")


def homework_load():
    global driver, wait, options
    # 打开网址
    driver.get("https://work.weixin.qq.com/")
    # 执行JavaScript代码，点击登录按钮
    driver.execute_script("document.querySelector('.index_top_operation_loginBtn').click()")
    # 等待页面跳转，判断是否登录成功
    wait.until(EC.url_contains("https://work.weixin.qq.com/wework_admin/frame"))
    # 获取登录后的cookie
    cookies = driver.get_cookies()
    # 将cookie写入文件里
    with open("./cookies.yml", "w") as f:
        for cookie in cookies:
            f.write(str(cookie) + "\n")

            # 读取cookie文件，并添加到浏览器中
    with open("./cookies.yml", "r") as f:
        cookies = json.load(f)
        for cookie in cookies:
            driver.add_cookie(cookie)

            # 刷新页面
    driver.navigate().refresh()

    # 定位元素并点击“通讯录”选项
    tongxunlu = driver.find_element(By.XPATH, "//*[text() ='通讯录']")
    driver.execute_script("arguments[0].click()", tongxunlu)

    # 等待元素加载，并定位到“添加成员”按钮并点击
    add = wait.until(EC.element_to_be_clickable((By.XPATH,
                                                 "//*[@class ='js_has_member']/*[@class ='ww_operationBar']//*[@class ='qui_btn ww_btn js_add_member']")))
    add.click()

    # 执行JavaScript代码，设置表单字段值
    js_name = "document.querySelector('#username').value ='符暖琴'"
    js_account = "document.querySelector('#memberAdd_acctid').value='520520123'"
    js_email = "document.querySelector('#memberAdd_mail').value='1417090203@qq.com'"
    driver.execute_script(js_name)
    driver.execute_script(js_account)
    driver.execute_script(js_email)

    # 定位并点击“继续添加”按钮
    driver.find_element(By.XPATH,"//*[@class ='qui_btn ww_btn ww_btn_Blue js_btn_continue']").click();